package com.ella.common.security.handler;
import com.alibaba.fastjson2.JSON;
import com.ella.entity.security.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 * 需要注意的是，AuthenticationEntryPoint 接口通常情况下只会在用户访问需要进行身份验证的资源时
 * （例如需要登录后才能访问的资源）才会被调用。对于无需进行身份验证的资源，例如静态资源等，
 * AuthenticationEntryPoint 接口不会被触发。
 * @author ruoyi
 */
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //捕获用户验证登录的异常
        ResponseResult<Integer> result = new ResponseResult<>(HttpStatus.UNAUTHORIZED.value(), "用户认证失败，请查询登录");
        String json = JSON.toJSONString(result);
        log.info("用户验证失败");
        //将信息写入响应体中
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(json);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }
}
